package com.hbnu.aop;

import com.hbnu.anno.Log;
import com.hbnu.domain.OperateLog;
import com.hbnu.mapper.OperateLogMapper;
import com.hbnu.utils.CurrentHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @version: 1.0
 * @ClassName: OperateLogAspect
 * @Description: TODO
 * @Author: 86132
 * @Date: 2025/11/19 10:17
 */
@Aspect
@Component
public class OperateLogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.hbnu.anno.Log)")
    public Object logOperation(ProceedingJoinPoint joinPoint) throws Throwable {
        //方法开始
        long startTime = System.currentTimeMillis();
        // 执行目标方法
        Object result = joinPoint.proceed();
        // 方法结束
        long endTime = System.currentTimeMillis();
        long costTime = endTime - startTime;
        // 创建OperateLog对象并保存到数据库
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateEmpId(getOperateEmpId());
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(joinPoint.getTarget().getClass().getName());
        operateLog.setMethodName(joinPoint.getSignature().getName());
        operateLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));
        operateLog.setReturnValue(result != null ? result.toString() : "void");
        operateLog.setCostTime(costTime);

        //保存日志
        operateLogMapper.insert(operateLog);

        //返回执行原始方法的结果
        return result;
    }

    private Integer getOperateEmpId() {
        // 实现获取当前登录用户id的逻辑
        return CurrentHolder.getCurrentId();
    }

}